package cn.walls1717.wallsmall.order.web;

import cn.walls1717.wallsmall.order.config.AlipayTemplate;
import cn.walls1717.wallsmall.order.pojo.vo.PayAsyncVO;
import cn.walls1717.wallsmall.order.service.OrderService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝付款状态
 *
 * @author walls1717
 * @since 2022/11/24 14:42
 **/
@RestController
@Slf4j
public class OrderPayedController {
    @Resource
    private OrderService orderService;
    @Resource
    private AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String AlipayHandler(PayAsyncVO payAsyncVO, HttpServletRequest request) throws AlipayApiException {

        log.info("payAsyncVO -> {}", payAsyncVO);
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
            alipayTemplate.getCharset(), alipayTemplate.getSign_type());

        if (!signVerified) {
            log.warn("签名验证失败");
            return "error";
        }

        log.info("签名验证成功");
        return orderService.payResultHandler(payAsyncVO);
    }
}
